package com.upbos.upm.common;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.upbos.upm.cfg.CfgUtil;
import com.upbos.upm.entity.Cfg;

import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;

/**
 * 加密密码，支持md5和des加密方式
 * @author wangjz
 */
public class PasswordSecureUtil {

    private static final String md5 = "md5";

    private static final String des = "des";

    public static String encrypt(String password) throws InvalidKeyException {
        // 获取密码加密方式
        Cfg cfg = CfgUtil.getCfg(Constants.USER_PASSWORD_ENCRYPT_TYPE_KEY);
        String encryptType = cfg == null ? des : cfg.getValue().toLowerCase();

        // 获取密码盐
        Cfg saltCfg = CfgUtil.getCfg(Constants.USER_PASSWORD_SALT_KEY);
        String salt = saltCfg == null ? "" : saltCfg.getValue().toLowerCase();

        String encryptPassword = password + salt;
        if (encryptType.equals(md5)) {
            encryptPassword = SecureUtil.md5(encryptPassword);
        } else {
            byte[] md5 = SecureUtil.md5().digest(Constants.PASSWORD_ENCRYPT_KEY);
            byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), new DESKeySpec(md5)).getEncoded();
            encryptPassword = SecureUtil.des(key).encryptBase64(encryptPassword);
        }
        return encryptPassword;
    }
}
